package com.faf.ui;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.faf.bean.Detail;
import com.faf.bean.Food;
import com.faf.bean.Orders;
import com.faf.dao.OrdersDao;
import com.faf.dao.impl.DetailDaoImpl;
import com.faf.dao.impl.FoodDaoImpl;
import com.faf.dao.impl.OrdersDaoImpl;
import com.faf.dao.impl.UserDaoImpl;

/**
 * Servlet implementation class PlaceOrder
 */
@WebServlet("/PlaceOrder")
public class PlaceOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PlaceOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		Object obj_ordernumber = request.getParameter("order");
		
		if(null != obj_ordernumber) {
		String orderNumber = obj_ordernumber.toString();
		DetailDaoImpl detailDao = new DetailDaoImpl();
		FoodDaoImpl foodDaoImpl = new FoodDaoImpl();
		
		List<Detail> placeorder_data_detail = detailDao.getDetailListByorderNumber(orderNumber);
		HashMap<Integer, Food> placeorder_data_foodmap = new HashMap<Integer, Food>();
		
		for(Detail detail : placeorder_data_detail) {
			try {
				placeorder_data_foodmap.put(detail.getFoodId(), foodDaoImpl.getFoodByFoodID(detail.getFoodId()));
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		request.setAttribute("orderNumber", orderNumber);
		request.setAttribute("placeorder_data_detail", placeorder_data_detail);
		request.setAttribute("placeorder_data_foodmap", placeorder_data_foodmap);
		
		request.getRequestDispatcher("/UserGlobal/place_order.jsp").forward(request, response);
		}
		else {
			String storeid = request.getParameter("storeid").toString();
			System.out.println("storeid = " + storeid);
			DetailDaoImpl detailDao = new DetailDaoImpl();
			FoodDaoImpl foodDaoImpl = new FoodDaoImpl();
			
			HashMap<Integer, Integer> global_info_cart_id2count = (HashMap<Integer, Integer>)request.getSession().getAttribute("global_cart");
			
			ArrayList<Food> foodList = new ArrayList<Food>();
			
			for(HashMap.Entry<Integer,Integer> entry : global_info_cart_id2count.entrySet()) {
				Food food;
				try {
					food = foodDaoImpl.getFoodByFoodID(entry.getKey());
					if(food.getStoreId() == Integer.parseInt(storeid))
						foodList.add(food);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("foodlist.size = " + foodList.size());
			
			//生成订单
			UserDaoImpl userDao = new UserDaoImpl();
			int userId = 0;
			try {
				userId = userDao.getUserByNumber(request.getSession().getAttribute("account").toString()).getUserId();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return;
			}
			System.out.println("userid = " + userId);
			
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat simpleDateFormat_on = new SimpleDateFormat("sssHHMMmmyyyydd");
			String orderNumber = simpleDateFormat_on.format(new Date(System.currentTimeMillis()));
			
			Orders order = new Orders(
					-1,
					orderNumber,
					userId,
					Integer.parseInt(storeid),
					-1,
					simpleDateFormat.format(new Date(System.currentTimeMillis())),
					null);
			
			OrdersDaoImpl orderDao = new OrdersDaoImpl();
			
			try {
				orderDao.insert(order);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			
			// 生成明细
			
			for(Food food : foodList) {
				//int detailId, String orderNumber, int foodId, int foodNumber, String messageRemark
				Detail detail = new Detail(
						0,
						orderNumber,
						food.getFoodId(),
						global_info_cart_id2count.get(food.getFoodId()),
						"");
				detailDao.insert(detail);
			}
			
			
			List<Detail> placeorder_data_detail = detailDao.getDetailListByorderNumber(orderNumber);
			HashMap<Integer, Food> placeorder_data_foodmap = new HashMap<Integer, Food>();
			
			for(Detail detail : placeorder_data_detail) {
				try {
					placeorder_data_foodmap.put(detail.getFoodId(), foodDaoImpl.getFoodByFoodID(detail.getFoodId()));
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			// 购物车删除
			for(Food food : foodList)
				global_info_cart_id2count.remove(food.getFoodId());
			request.getSession().setAttribute("global_info_cart_id2count", global_info_cart_id2count);
			
			
			request.setAttribute("orderNumber", orderNumber);
			request.setAttribute("placeorder_data_detail", placeorder_data_detail);
			request.setAttribute("placeorder_data_foodmap", placeorder_data_foodmap);
			
			request.getRequestDispatcher("/UserGlobal/place_order.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
